package com.liyuan.help_e.controller;

import com.liyuan.help_e.model.Question;
import com.liyuan.help_e.model.ResultJson;
import com.liyuan.help_e.model.Tags;
import com.liyuan.help_e.service.QuestionService;
import com.liyuan.help_e.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Controller
public class PublishController {
    @Autowired
    QuestionService questionService;
    @Autowired
    TagService tagService;

    @GetMapping("/publish")
    public void publish_Html(HttpServletResponse response,
                             HttpServletRequest request) throws ServletException, IOException {
        request.getRequestDispatcher("/publish.html").forward(request,response);
    }

    @ResponseBody
    @GetMapping("/publish/tags")
    public ResultJson tags() {
        Map<String, Tags[]> map = tagService.getTags();
        return new ResultJson(200, "get tags success", map);
    }

    @PostMapping("/publish")
    public String publish(Question question) {
        if (question.getId() != null) {
            questionService.updateQuestion(question);
        } else {
            questionService.insertQuestion(question);
        }
        return "redirect:/";
    }
}
